//
//@author jltxseo
// Created by junlintianxia on 2019/10/13.
//



#include <string>
#include "ShaderHelper.h"
#include "XqLog.h"
#include <cstring>
#define  LOG_TAG    "ShaderHelper"

void ShaderHelper::setEnvAndAssetManager(JNIEnv *env, jobject assetManager) {
    sEnv = env;
    sAssetManager = assetManager;
}

/**
 *根据文件名打开资源文件
 * @param assetFilePath
 * @return
 */
AAsset *ShaderHelper::loadAsset(const char *assetFilePath)
{
    AAssetManager *nativeAssetManager = AAssetManager_fromJava(sEnv,sAssetManager);
    if(nativeAssetManager == NULL){
        return NULL;
    }
    return AAssetManager_open(nativeAssetManager,assetFilePath,AASSET_MODE_UNKNOWN);
}

/**
 * 传入着色器文件路径，读取着色器代码
 * @param shaderCode   传入回传着色器代码指针
 * @param shadeFilePath 传入文件路径指针
 * @return  fasle:读取失败  true：读取成功
 */
char * ShaderHelper::readShaderCodeFromFile(const char *shadeFilePath)
{
    std::string shaderCode;
    // Read the Fragment Shader code from the file
    AAsset *asset = loadAsset(shadeFilePath);
    if(asset == NULL){
        LOGE(LOG_TAG,"Impossible to open %s. Are you in the right directory ? Don't forget to read the FAQ !\n", shadeFilePath);
        shaderCode =  "";
    } else{
        //获取文件长度
        off_t length = AAsset_getLength(asset);
        char *buffer = new char[length + 1];
        int num = AAsset_read(asset, buffer,length);
        AAsset_close(asset);
        if(num != length){
            LOGE(LOG_TAG,"Couldn't read %s", shadeFilePath);
            delete[] buffer;
            shaderCode = "";
        }
        buffer[length] = '\0';
        shaderCode = buffer;
    }
    //string 对象转换成c中的字符串样式.
    //注意：一定要使用strcpy()函数 等来操作方法c_str()返回的指针
    int len = shaderCode.length();
    char *result = new char[len];
    //c_str  是标准的做法
    strcpy(result, shaderCode.c_str());
    return result;
}

const bool ShaderHelper::loadTexturePixelsFromBitmap(void **data, int *width, int *height,
                                                     jobject bitmap) {
    LOGD(LOG_TAG,"loadTexture");
    AndroidBitmapInfo bitmapInfo;
    int ret;
    //AndroidBitmap_getInfo 函数允许原生代码检索 Bitmap 对象信息，如它的大小、像素格式等，
    if ((ret = AndroidBitmap_getInfo(sEnv, bitmap, &bitmapInfo)) < 0) {
        LOGE(LOG_TAG,"AndroidBitmap_getInfo() failed ! error=%d", ret);
        return false;
    }

    // 读取 bitmap 的像素内容到 native 内存
    if ((ret = AndroidBitmap_lockPixels(sEnv, bitmap, data)) < 0) {
        LOGE(LOG_TAG,"AndroidBitmap_lockPixels() failed  error=%d", ret);
        return false;
    }

    *width = bitmapInfo.width;
    *height = bitmapInfo.height;
    //释放原生像素缓存
    AndroidBitmap_unlockPixels(sEnv, bitmap);

    return true;
}